class ApplicationController < ActionController::Base
  protect_from_forgery
  
  before_filter :error_message_follows_field,
    :current_user_id,
    :authorize
    
  # 校验错误信息显示在field后面
  def error_message_follows_field
    error_message_follows_field_by_default
  end
  
  def error_message_follows_field_by_default
    ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|      
      if instance.error_message.kind_of?(Array)
        %(#{html_tag}<span class="validation_error">&nbsp;#{instance.error_message.join(',')}</span>).html_safe

      else
        %(#{html_tag}<span class= "validation_error">&nbsp;#{instance.error_message}</span>).html_safe
      end
    end
  end
  
  def error_message_follows_field_in_new_line
    ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|      
      if instance.error_message.kind_of?(Array)
        %(#{html_tag}<span class="validation_error"><br/>#{instance.error_message.join(',')}</span>).html_safe

      else
        %(#{html_tag}<span class= "validation_error"><br/>#{instance.error_message}</span>).html_safe
      end
    end
  end
  
  def current_user
    User.find(current_user_id) if current_user_id.present?
  end
  
  def current_user_id
    if session[:current_user_id].nil? and cookies.signed[:user_id].present?
      begin
        user = User.find(cookies.signed[:user_id])
        session[:current_user_id] = user.id if user.check_security_key_in_cookies(cookies.signed[:user_security_key])        
      rescue ActiveRecord::RecordNotFound
        logger.debug "user.find(#{cookies.signed[:user_id]}) failed"
      end
    else
#      logger.debug "验证当前会员是否可用"
      session[:current_user_id] = nil if not User.exists?(session[:current_user_id])
    end          
    Thread.current[:current_user_id] = session[:current_user_id]
    session[:current_user_id]
  end
  
  def authorize
    respond_to do |format|
      format.html do         
        redirect_to new_session_url :http_referer => request.request_uri
      end
      format.js do
        redirect_to new_session_url(:format => :js)
      end
    end if not User.has_loggined? or User.current.status.locked?
  end
end
